package cn.hou.java8;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

import org.junit.Test;


public class TestLambda {
	
	List<Employee> emps=Arrays.asList(
			new Employee("哈哈",18),
			new Employee("呵呵",16),
			new Employee("嘿嘿",20),
			new Employee("呼呼",18)
	);
	@Test
	public void test01(){
		//对员工排序,先按年龄排序,如果相等,再按名字排序
		//lambda实现排序器
		Collections.sort(emps, (e1,e2)->{
			if(e1.getAge()==e2.getAge()){
				return e1.getName().compareTo(e2.getName());
			}else{
				return Integer.compare(e1.getAge(), e2.getAge());
			}
		});
		//输出集合,foreach参数需要一个函数式接口的实现
		emps.forEach(x->System.out.println(x));
	}
	
	@Test
	public void test02(){
		//1 字符串转大写
		String result01 = strOperation("houzheng",str->{
			return str.toUpperCase();
		});
		System.out.println(result01);// HOUZHENG
		//2 截取子字符串,索引2到4 (左闭右开)
		String result02=strOperation("houzheng",str->{
			return str.substring(2, 4);
		});
		System.out.println(result02);// uz
	}
	
	//字符串操作方法
	public String strOperation(String string,MyStringOperation msp){
		return msp.getValue(string);
	}
	
	@Test
	public void test03(){
		//1求和,输出String类型
		String add = getResult(100,200,(x,y)->x+y+"");
		System.out.println(add);
		//2求积
		String product = getResult(100,200,(x,y)->x*y+"");
		System.out.println(product);
	}
	//传入两个Integer数,求运算结果 ,泛型必须传对象,不能是基本类型
	public String getResult(int t1,int t2,MyNumOperation<Integer, String> mlp){
		return mlp.getValue(t1, t2);
	}
	@Test
	public void test04(){
		//四大内置函数可以直接使用而不必去声明函数式接口,除非有特殊需求需要单独声明
		//1 消费型接口,传入参数无返回
		Consumer<String> com=x->System.out.println(x);
		com.accept("哈哈");//哈哈
		
		//2供给型接口,无参,有返回值
		Supplier<String> sup=()->"9527";
		System.out.println(sup.get());//9527
		
		//3 函数型接口,有参数有返回值
		Function<String,Integer> fun=(s)->Integer.valueOf(s);
		System.out.println(fun.apply("666"));//666
		
		//4断言型接口,传入参数,返回boolean
		Predicate<String> pre=x->x!="";
		System.out.println(pre.test(""));//false
		
	}
	
	@Test
	public void test05(){}

}
